<template>
  <el-dialog
    :visible.sync="innerVisible"
    width="1000px"
    title="选择需要显示的列"
    :close-on-click-modal="false"
    center
    append-to-body
    top="30vh">
    <div class="checkbox-all">
      <el-checkbox v-model="allChecked">全选</el-checkbox>
    </div>
    <div class="checkbox-wrap">
      <el-checkbox
        v-for="(item) in columns"
        :key="item.prop"
        v-model="item._visible"
        @change="handleChange(item)"
      >
        {{ item.label }}
      </el-checkbox>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="default" size="mini" @click="innerVisible=false">取消</el-button>
      <el-button type="primary" size="mini" @click="handleVisibleMap">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>


export default {
  name: 'ColSelector',
  props: {
    option: {
      type: Object,
      default() {
        return {}
      }
    },
    visibleMap: {
      type: Object,
      default() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      innerVisible: false,
      columns: []
    }
  },
  computed: {
    allChecked: {
      get() {
        return !this.columns.some(el => !el._visible)
      },
      set(v) {
        this.columns.forEach(c => {
          c._visible = v
        })
      }
    }
  },
  watch: {
    innerVisible() {
      this.$emit('update:visible', this.innerVisible)
      if (this.innerVisible) {
        this.calcColumns()
      }
    },
    visible() {
      this.innerVisible = this.visible
    },
    option() {
      this.calcColumns()
    }
  },
  created() {
    // this.calcColumns()
  },
  methods: {
    calcColumns() {
      this.columns = (this.option.columns || []).filter(el => !el.hiddenInTable).map(el => {
        return {...el, _visible: el.prop in this.visibleMap ? this.visibleMap[el.prop] : true}
      })
    },
    handleChange(item) {
      // this.$emit('update:visibleMap', {...this.visibleMap, [item.prop]: item._visible})
    },
    handleVisibleMap() {
      this.innerVisible = false
      setTimeout(() => {
        this.$emit('update:visibleMap', this.columns.filter(el => !el._visible).reduce((r, a) => {
          r[a.prop] = false
          return r
        }, {}))
      }, 20)
    }
  }
}
</script>

<style scoped lang="scss">
.checkbox-wrap {
  padding-left: 20px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 20px;
}

.checkbox-all {
  padding-left: 20px;
  padding-bottom: 20px;
}
</style>
